<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use App\Http\Resources\Result;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * 全局异常处理
     */
    public function render($request, Throwable $e)
    {
        $code = $this->getHttpCode($e);
        if($e instanceof AuthenticationException) {
            $code = 401;
        } else if($e instanceof ValidationException) {
            $code = 422;
        }
        // 所有异常均返回 JSON
        return Result::FAIL($code,
            $e->getMessage(),
            $this->getErrors($e));
    }

    private function getHttpCode(Throwable $e): int
    {
        return method_exists($e, 'getStatusCode')
        ? $e->getStatusCode()
        : 500;
    }
    private function getErrors(Throwable $e)
    {
        return method_exists($e, 'errors')
        ? $e->errors()
        : null;
    }
}
